<template>
  <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-15个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option
          v-for="item in list"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployeesSimple } from '@/api/employees'
import { addDepartments, getDepartmentsById, updateDepartments } from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    origin: {
      type: Array,
      required: true
    }
  },
  data() {
    // 校验编码在项目中是否重复 -- 自定义校验
    const validCode = (rule, value, callback) => {
      // 1.如果当前部门的编码已经存在，提示用户重新重复
      let exitCodeList = this.origin.map(item => item.code)
      console.log('exitCodeList', exitCodeList)
      // 如果是编辑状态，把当前是部门的编辑从已经存在的数据中移除
      if (this.isEdit) {
        exitCodeList = this.origin.filter(item => item.id !== this.id).map(item => item.code)
      }
      if (exitCodeList.includes(value)) {
        callback(new Error(`该部门的编码：${value}已经存在，请重新输入`))
      } else {
        // 不存在 不提示 放行
        callback()
      }
    }
    // 校验同级中编辑的状态，把当前是部门的编辑从已经存在的数组中移除
    const validName = (rule, value, callback) => {
      // 找到当前点击的部门的子级
      let exitCodeName = this.origin.filter(item => item.pid === this.id).map(item => item.name)

      if (this.isEdit) {
        // 如果是编辑状态 -- 获取当前的pid
        const pid = this.origin(item => item.id === this.id).pid
        // 获取被占用的名称列表
        exitCodeName = this.origin.filter(item => item.pid === pid).filter(item => item.id !== this.id).map(item => item.name)
      }
      // 判断当前用户输入的部门名称是否已经存在
      if (exitCodeName.includes(value)) {
        callback(new Error(`该部门名称：${value}已经存在，请重新输入`))
      } else {
        // 不存在 不提示 放行
        callback()
      }
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }

        ],
        manager: [
          { required: true, message: '请输入部门的负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门的介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '长度在 1 到 300 个字符', trigger: 'blur' }
        ]
      },
      list: [] // 保存负责人信息
    }
  },
  created() {
    this.loadEmployeeSimple()
    if (this.isEdit) {
      this.loadDepartmentsById()
    }
  },
  methods: {
    // 获取部门负责人列表
    async loadEmployeeSimple() {
      try {
        const res = await getEmployeesSimple()
        console.log(res, '获取部门负责人信息')
        this.list = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 新增子部门
    async doAdd() {
      try {
        const res = await addDepartments({ ...this.form, pid: this.id })
        console.log(res, '新增子部门')
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 获取部门详情
    async  loadDepartmentsById() {
      try {
        const res = await getDepartmentsById(this.id)
        console.log('res获取部门详情', res)
        this.form = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑部门
    async doEdit() {
      try {
        const res = await updateDepartments(this.form)
        console.log('res编辑部门', res)
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 确认按钮
    hSubmit() {
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 取消按钮
    hCancel() {
      this.$emit('close')
    },
    // 清空表单
    resetForm() {
      this.$refs.deptForm.resetFields()
    }
  }
}
</script>
